package com.taoym.voucher.xcx.service.impl;

import com.taoym.voucher.common.enums.ImageSuffixEnum;
import com.taoym.voucher.common.response.ResponseStatusCode;
import com.taoym.voucher.common.utils.ExceptionCore;
import com.taoym.voucher.xcx.service.FilesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
@Slf4j
public class FilesServiceImpl implements FilesService {

    @Value(value = "${file.upload}")
    private String filePath;
    @Value(value = "${nginx.path}")
    private String nginxAddress;

    @Override
    public String upload(MultipartFile files) {
        String fileUrl = generatorFileUrl(files);
        // 取处理后的文件名称
        String fileName = fileUrl.replace(nginxAddress, "");

        Path path = Paths.get(filePath + fileName);
        byte[] bytes = new byte[0];
        try {
            bytes = files.getBytes();
            Files.write(path, bytes);
        } catch (IOException e) {
            throw new ExceptionCore(ResponseStatusCode.FILE_UPLOAD_FAIL);
        }
        return nginxAddress + fileName;
    }

    @Override
    public String delete(String url) {
        String fileName = url.replace(nginxAddress, "");
        Path path = Paths.get(filePath + fileName);
        try {
            Files.delete(path);
        } catch (IOException e) {
            log.warn("file delete is fail {}", url);
            return "删除失败";
        }
        return "删除成功";
    }

    private String generatorFileUrl(MultipartFile files) {
        if (files == null) {
            throw new ExceptionCore(ResponseStatusCode.FILE_UPLOAD_FAIL);
        }
        // 获取文件名称
        String fileName = files.getOriginalFilename();
        //获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        if (!ImageSuffixEnum.getImageSuffix(suffixName)) {
            throw new ExceptionCore(ResponseStatusCode.FILE_UPLOAD_FAIL);
        }
        //重新生成文件名
        fileName = UUID.randomUUID() + suffixName;
        // 返回的是图片的访问地址
        return nginxAddress + fileName;
    }
}
